import { createIntl, createIntlCache } from '@formatjs/intl';
import messages from '@/locale';
import { Lang } from '@/apps';
import { IntlShape } from 'react-intl';
import type { NextRouter } from 'next/router';

// This is optional but highly recommended
// since it prevents memory leak
const cache = createIntlCache();

// Create the `intl` object
export const getLocale = ({ lang }: Lang) => {
  const intl = createIntl(
    {
      // Locale of the application
      locale: lang,
      // Locale of the fallback defaultMessage
      defaultLocale: lang,
      messages: messages[lang],
    },
    cache
  );
  return intl;
};

export const getLangByIntl = (intl: IntlShape): Lang => {
  const lang: Lang = { lang: 'zh-CN' };
  if (intl.locale == 'zh-CN') {
    lang.lang = intl.locale;
  }
  if (intl.locale == 'en-US') {
    lang.lang = intl.locale;
  }
  return lang;
};
export const getLangByRouter = (router: NextRouter): Lang => {
  const lang: Lang = { lang: 'zh-CN' };
  if (router.locale == 'zh-CN') {
    lang.lang = router.locale;
  }
  if (router.locale == 'en-US') {
    lang.lang = router.locale;
  }
  return lang;
};
